<template>

  <div class="dashboard-container">
    <el-row :gutter="20">
      <!-- 货源新增折线图 -->
      <el-col :span="18">
        <div v-loading="productChangeLoading" class="chart-card">
          <div class="chart-title">货源新增趋势</div>
          <div id="productChangeChart" class="chart-content"></div>
          <el-form :inline="true" label-width="60px" class="filter-form">
            <el-form-item label="维度">
              <el-select v-model="productChangeQuery.timeType" @change="productHandleTimeTypeChange">
                <el-option label="天" value="day"></el-option>
                <el-option label="月" value="month"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="范围">
              <el-date-picker
                v-model="productChangeQuery.timeRange"
                :type="productChangeQuery.timeType === 'day' ? 'daterange' : 'monthrange'"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="类目">
              <el-select v-model="productChangeQuery.className" clearable>
                <el-option
                  v-for="dict in dict.type.amazon_us_class_name"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="平台">
              <el-select v-model="productChangeQuery.platform" clearable>
                <el-option
                  v-for="dict in dict.type.basic_platform"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="getProductChangeChartData"> 刷 新</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <!-- 品牌剩余数量柱状图 -->
<!--      <el-col :span="13">-->
<!--        <div v-loading="remainUploadLoading" class="chart-card">-->
<!--          <div class="chart-title">AmazonUS类目剩余可上传数量</div>-->
<!--          <div id="remainUploadChart" class="chart-content"></div>-->
<!--          <el-form :inline="true" label-width="100px" class="filter-form">-->
<!--            <el-form-item label="平台" required>-->
<!--              <el-select-->
<!--                v-model="remainUploadQuery.platform"-->
<!--                placeholder="请选择平台"-->
<!--              >-->
<!--                <el-option-->
<!--                  v-for="dict in dict.type.basic_platform"-->
<!--                  :key="dict.value"-->
<!--                  :label="dict.label"-->
<!--                  :value="dict.value"-->
<!--                ></el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="品牌" required>-->
<!--              <el-select-->
<!--                v-model="remainUploadQuery.brand"-->
<!--                placeholder="请选择品牌"-->
<!--                filterable-->
<!--              >-->
<!--                <el-option-->
<!--                  v-for="dict in dict.type.brand_list"-->
<!--                  :key="dict.value"-->
<!--                  :label="dict.label"-->
<!--                  :value="dict.value"-->
<!--                ></el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--            <el-form-item>-->
<!--              <el-button type="primary" @click="getRemainUploadChartData"> 刷 新</el-button>-->
<!--            </el-form-item>-->
<!--          </el-form>-->
<!--        </div>-->
<!--      </el-col>-->
    </el-row>

    <el-row :gutter="20">

      <el-col :span="18">
        <div v-loading="shopQuantityLoading" class="chart-card">
          <div class="chart-title">AmazonUS店铺库存分布(三天前)</div>
          <div class="chart-subtitle" style="margin-left: 30px; padding: 10px">外环: 总库存 | 内环: 低库存(≤4)</div>
          <div class="chart-subtitle" style="margin-left: 30px; padding: 10px"> {{ shopQuantityTotalStr }}</div>
          <div id="shopQuantityChart" class="chart-content" style="height:550px"></div>
          <el-form :inline="true" class="filter-form">
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>

</template>

<script>
import * as echarts from 'echarts'
import { getProductAddChange, getRemainUpload, getShopQuantity } from '@/api/index'

import globalMixins from '@/utils/globalMixins'

export default {
  dicts: ['seller_platform', 'amazon_us_class_name', 'basic_platform', 'brand_list'],
  data() {
    return {
      pickerOptions: {},

      //货源
      productChangeLoading: false,
      productChangeQuery: {
        className: '',
        platform: '',
        timeType: 'day',
        timeRange: []
      },
      productChangeChart: null,
      productChangeChartData: [],
      //剩余可上传
      remainUploadLoading: false,
      remainUploadQuery: {
        platform: 'GG',
        brand: 'TREATLIFE HOME'
      },
      remainUploadChart: null,
      remainUploadChartData: [],

      shopQuantityLoading: false,
      shopQuantityChart: null,
      shopQuantityChartData: [],
      shopQuantityTotalStr:'',
      shopQuantityQuery: {
        platform: '',
        timeType: 'day',
        timeRange: []
      }

    }
  },
  mounted() {
    this.pickerOptions = globalMixins.data().pickerOptions
    // 挂载图表
    this.productChangeChart = echarts.init(document.getElementById('productChangeChart'))
    //this.remainUploadChart = echarts.init(document.getElementById('remainUploadChart'))
    this.shopQuantityChart = echarts.init(document.getElementById('shopQuantityChart'))
    this.productChangeQuery.timeRange = this.getLastWeekDefaultTimeRange()

    this.getProductChangeChartData()
    // this.getRemainUploadChartData()
    this.getShopQuantityChartData()
  },
  methods: {
    //货源新增变化
    // 切换时间维度时重置时间范围
    productHandleTimeTypeChange() {
      this.productChangeQuery.timeRange = []
    },

    getProductChangeChartData() {
      if (!this.productChangeQuery.timeRange || this.productChangeQuery.timeRange.length !== 2) return
      let productParams = {
        timeType: this.productChangeQuery.timeType,
        startTime: this.formatDate(this.productChangeQuery.timeRange[0], this.productChangeQuery.timeType),
        endTime: this.formatDate(this.productChangeQuery.timeRange[1], this.productChangeQuery.timeType),
        className: this.productChangeQuery.className || null,
        platform: this.productChangeQuery.platform || null
      }
      this.productChangeLoading = true
      getProductAddChange(productParams).then(response => {
        this.productChangeChartData = response
        this.productChangeLoading = false
        this.updateProductChangeChart()
      })
    },
    // 更新渲染货源图表
    updateProductChangeChart() {
      const option = {
        // title: {text: '货源新增'},
        tooltip: { trigger: 'axis' },
        xAxis: {
          type: 'category',
          data: this.productChangeChartData.map(item => item.time),
          axisLabel: {
            formatter: (value) =>
              this.timeType === 'day' ? value.split('-').join('/') : value
          }
        },
        yAxis: { type: 'value' },
        series: [{
          data: this.productChangeChartData.map(item => item.count),
          type: 'line',
          smooth: true,
          areaStyle: { color: '#409EFF20' },
          lineStyle: { color: '#409EFF' }
        }]
      }
      this.productChangeChart.setOption(option)
    },

    getRemainUploadChartData() {
      if (!this.remainUploadQuery.platform || !this.remainUploadQuery.brand) return
      let remainUploadParams = {
        platform: this.remainUploadQuery.platform,
        brand: this.remainUploadQuery.brand
      }
      this.remainUploadLoading = true
      getRemainUpload(remainUploadParams).then(response => {
        this.remainUploadChartData = response
        this.remainUploadLoading = false
        this.updateRemainUploadChart()
      })
    },

    // 更剩余可上传图表
    updateRemainUploadChart() {
      const option = {
        // title: { text: '剩余可上传数量' },
        width: '100%',
        tooltip: { trigger: 'axis' },
        xAxis: {
          type: 'category',
          data: this.remainUploadChartData.map(item => item.className),
          axisLabel: {
            rotate: 90 // 类目名称较长时旋转
          }
        },
        yAxis: { type: 'value' },
        series: [{
          data: this.remainUploadChartData.map(item => item.remainCount),
          type: 'bar',
          itemStyle: {
            color: '#36a3f7'
          }
        }]
      }
      this.remainUploadChart.setOption(option)
    },

    getShopQuantityChartData() {

      this.shopQuantityLoading = true
      getShopQuantity({}).then(response => {
        this.shopQuantityChartData = response
        this.shopQuantityLoading = false
        this.updateShopQuantityChart()
      })
    },
    updateShopQuantityChart() {
      const colors = [
        '#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE',
        '#9A60B4', '#3BA272', '#FC8452', '#EA7CCC', '#FCDD3D',
        '#4EA397', '#75C2D6', '#D7504B', '#C14089', '#26C0C0',
        '#F4E001', '#B5C334', '#F58FDB', '#A48F21', '#7C4B00',
        '#B09B87', '#6E7074', '#61A0A8', '#2F4554', '#D48265',
        '#C23531', '#749F83', '#CA8622', '#BDA29A', '#6E7783',
        '#008080', '#E08031', '#BAE7FF', '#D87C7C', '#8D98B3'
      ]
      const pieData = this.shopQuantityChartData.filter(item => item.shop !== 'Total').map(item => ({
        shop: item.shop,
        lowStock: item.lowStock,
        total: item.total
      }))
      console.log(pieData)
      const totalData = this.shopQuantityChartData.find(item => item.shop === 'Total')
      if (totalData) {
        this.shopQuantityTotalStr = `所有店铺SKU总数: ${totalData.total}, SKU低库存数: ${totalData.lowStock}`

      }
      const option = {
        color: colors,
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            const data = pieData.find(item => item.shop === params.name.split(' ')[0])
            return `
              <strong>${data.shop}</strong><br/>
              总库存: ${data.total}个SKU<br/>
              低库存: ${data.lowStock}个SKU<br/>
              低库存率: ${((data.lowStock / data.total) * 100).toFixed(1)}%
            `
          }
        },
        legend: {
          orient: 'vertical',
          left: 'right',
          formatter: (name) => {
            const shop = pieData.find(item => item.shop === name)
            return `${name} | 总:${shop.total} 低:${shop.lowStock}`
          }
        },
        series: [
          {
            name: '总库存',
            type: 'pie',
            radius: ['60%', '80%'],
            label: {
              show: false
            },
            data: pieData.map(item => ({
              name: item.shop,
              value: item.total
            }))
          },
          {
            name: '低库存',
            type: 'pie',
            radius: ['40%', '58%'],
            label: {
              show: false
            },
            data: pieData.map(item => ({
              name: item.shop,
              value: item.lowStock,
              itemStyle: {
                color: colors[pieData.indexOf(item) % colors.length]
              }
            }))
          }
        ]
      }

      this.shopQuantityChart.setOption(option)
    },

    getLastWeekDefaultTimeRange() {
      const now = new Date()
      const currentDayOfWeek = now.getDay() // 获取今天是周几（0表示周日，1表示周一...）
      // 上周开始时间（上周一）
      const startOfLastWeek = new Date(now.setDate(now.getDate() - currentDayOfWeek - 7 + 1))
      startOfLastWeek.setHours(0, 0, 0, 0) // 设置时间为当天的开始时间
      // 上周结束时间（上周末）
      const endOfLastWeek = new Date(now.setDate(startOfLastWeek.getDate() + 6))
      endOfLastWeek.setHours(23, 59, 59, 999) // 设置时间为当天的结束时间
      return [startOfLastWeek, endOfLastWeek]
    },

    formatDate(date, type) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return type === 'day' ? `${year}-${month}-${day}` : `${year}-${month}`
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.chart-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.chart-title {
  padding: 16px;
  font-size: 16px;
  font-weight: bold;
  border-bottom: 1px solid #eee;
}

.chart-content {
  width: 100%;
  height: 400px;
  padding: 16px;
}

.filter-form {
  padding: 16px;
}
</style>
